<template>
  <div class='area'>
    <div :id="`wordCloud${index}`"></div>
  </div>
</template>

<script>
  import DataSet from '@antv/data-set';
  import { Chart, registerShape, Util } from '@antv/g2';
  import { getTextAttrs } from '@/utils'

  export default {
    name: 'WordCloud',
    props: ['value','index'],
    data() {
      return {

      }
    },
    mounted() {
      this.initCharts()
    },
    methods: {
      initCharts() {
        // console.log('----',this.value)
        // 给point注册一个词云的shape
        registerShape('point', 'cloud', {
          draw(cfg, container) {
            const attrs = getTextAttrs(cfg);
            const textShape = container.addShape('text', {
              attrs: {
                ...attrs,
                x: cfg.x,
                y: cfg.y
              }
            });
            if (cfg.data.rotate) {
              Util.rotate(textShape, cfg.data.rotate * Math.PI / 180);
            }
            return textShape;
          }
        })

        const dv = new DataSet.View().source(this.value);
        const range = dv.range('value');
        const min = range[0];
        const max = range[1];
        dv.transform({
          type: 'tag-cloud',
          fields: ['varchar', 'value'],
          size: [300, 400],
          font: 'Verdana',
          padding: 0,
          timeInterval: 5000, // max execute time
          rotate() {
            let random = ~~(Math.random() * 4) % 4;
            if (random === 2) {
              random = 0;
            }
            return random * 90; // 0, 90, 270
          },
          fontSize(d) {
            if (d.value) {
              return ((d.value - min) / (max - min)) * (80 - 24) + 24;
            }
            return 0;
          }
        });
        const chart = new Chart({
          container: `wordCloud${this.index}`,
          autoFit: false,
          width: 300,
          height: 400,
          padding: [50, 50, 50, 50]

        });
        chart.data(dv.rows);
        chart.scale({
          x: { nice: false },
          y: { nice: false }
        });
        chart.legend(false);
        chart.axis(false);
        chart.tooltip({
          showTitle: false,
          showMarkers: false
        });
        chart.coordinate().reflect();
        chart.point()
          .position('x*y')
          .color('CornflowerBlue')
          .shape('cloud')
          .tooltip('value*varchar');
        chart.interaction('element-active');
        chart.render();
      }
    }
  }
</script>

<style scoped>
.area{
  display: flex;
  flex-direction: row;
  justify-content: center;
}
</style>
